
// pages/sign/index.js
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
  Page({
  /**
   * 页面的初始数据
   */
  data: {
    placeholder: '',
    drawed: false,
    title: '',
    imgSrc: '',
    createrOpenId: '',
    test: '1',
    isInputName: false,
    actionName: '',
    actionID: '',
    userInfo: {},
    isLogined: false,
    showUser: false
  },
  formSubmit() {
    let that_ = this;
    let timer = setTimeout(() => {
      that_.getQrcodeByCloud()
      clearTimeout(timer);
    }, 2000)
  },
  getQrcodeByCloud() {
    let that_ = this
    console.log('actionName ====', this.data.actionName)
    console.log('actionName ====', that_.data.actionID)
    wx.cloud.callFunction({
      name: 'getQRcode',
      data: {
        actionID: that_.data.actionID
      },
      success: res => {
        console.log(res)
        let buff = wx.arrayBufferToBase64(res.result.buffer)
        that_.setData({
          imgSrc: "data:image/PNG;base64,"+ buff
        })
        wx.hideToast();
        that_.setData({
          drawed :true
        })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },
  onGetOpenid: function() {
    // 调用云函数
    let that_ = this
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        that_.createrOpenId = res.result.openid
      }
    })
  },
  async gotoHistory() {
    if(!this.data.isLogined) {
      this.setData({
        showUser: true
      })
      return
    }
    console.log(this.actionID)
    wx.navigateTo({
      url: '../history/index?userOpenId=' + this.createrOpenId,
      success: () => {
        console.log('success')
      },
      fail: () => {
        console.log('fail')
      }
    })
  },
  async gotoDetail() {
    if(!this.data.isLogined) {
      this.setData({
        showUser: true
      })
      return
    }
    console.log(this.actionID)
    wx.navigateTo({
      url: '../detail/index?userOpenId=' + this.createrOpenId,
      success: () => {
        console.log('success')
      },
      fail: () => {
        console.log('fail')
      }
    })
  },
  onGetUserInfo: async function(e) {
    console.log(e)
    if (e.detail.userInfo) {
      await this.setData({
        userInfo: e.detail.userInfo,
        isLogined: true,
        showUser: false
      })
    }
  },
  onClose() {
    this.setData({
      showUser: false
    })
    wx.showToast({
      title: '授权失败',
      icon: 'none'
    })
  },
  // goto succes  
  async goToSuccess() {
    console.log(this.actionID)
    wx.navigateTo({
      url: '../signSuccess/index?actionID=' + this.data.actionID,
      success: () => {
        console.log('success')
      },
      fail: () => {
        console.log('fail')
      }
    })
  },
  getSettingFun() {
    let that = this
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          console.log(' get scope.userInfo')
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              that.setData({
                userInfo: res.userInfo,
                showUser: false,
                isLogined: true
              })
            }
          })
        }else {
          this.setData({
            isLogined: false,
            showUser: true
          })
          
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.onGetOpenid()
    this.getSettingFun()
  },
  inputName: function(e) {
    this.setData({
      actionName: e.detail,
    })
  },
  addAction:async function() {
    if(!this.data.isLogined) {
      this.setData({
        showUser: true
      })
      return
    }
    this.setData({
      isInputName: true,
      actionName: '',
      actionID: ''
    })
  },
  confirmAdd: function() {
    
    if(this.data.actionName === '') {
      Dialog.alert({
        tilte: '提示',
        message: '提交失败,活动名不能为空。',
        selector: '#van-dialog'
      }).then().catch()
      return
    }
    wx.showToast({
      title: '生成中',
      icon: 'loading',
      duration: 9999
    });
    let that = this
    wx.cloud.callFunction({
      name: 'addAction',
      data: {
        name: that.data.actionName,
        createrOpenId: that.createrOpenId,
        createrName: that.data.userInfo.nickName
      },
      success: res => {
        console.log(res.result._id)
        that.setData({
          actionID: res.result._id
        })
        that.formSubmit()
      }
    })
  },
  scan: function() {
    console.log(this.actionID)
    wx.scanCode({
      onlyFromCamera: true,
      success (res) {
        console.log(res)
      }
    })
  },
  save() {
    wx.saveImageToPhotosAlbum({
      filePath: this.imgSrc,
    })
  }
})